package com.wego.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wego.bean.PageBean;
import com.wego.domain.UserInfo;
import com.wego.domain.dto.UserLoginDTO;
import com.wego.domain.entity.User;
import com.wego.domain.query.UserQuery;
import com.wego.domain.vo.UserVO;
import com.wego.mapper.UserMapper;
import com.wego.service.UserService;
import com.wego.utils.JwtUtils;
import com.wego.utils.Md5Util;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public UserInfo login(UserLoginDTO loginDTO) {
        final User e = userMapper.selectByAccount(loginDTO.getAccount());
        if (e == null) {
            return null;
        }
        // 使用Md5Util的verify方法进行密码验证，更加清晰和符合工具类的设计意图
        if (Md5Util.verify(loginDTO.getPassword(), e.getSalt(), e.getPassword())) {
            log.info("登录成功, 员工信息: {}", e);
            //生成JWT令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("nickname", e.getNickname());
            String jwt = JwtUtils.generateToken(claims);

            return new UserInfo(e.getId(), e.getNickname(),jwt, e.getAvatar());
        }
        return null;
    }

    @Override
    public List<UserVO> getList() {
        return userMapper.selectList();
    }


    @Override
    public PageBean<User> getPage(UserQuery userQuery) {
        log.info("获取第{}页，{}条数据", userQuery.getPageNum(), userQuery.getPageSize());
        final Integer pageNum = userQuery.getPageNum();
        final Integer pageSize = userQuery.getPageSize();
        final Page<User> page = PageHelper.startPage(pageNum, pageSize);
        userMapper.selectWithCondition(userQuery);
        return PageBean.page2pageBean(page);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public int insert(User user) {
        if (user == null) {
            throw new IllegalArgumentException("User cannot be null");
        }
        if (user.getNickname() == null) {
            throw new IllegalArgumentException("Nickname cannot be null");
        }
        if (user.getAccount() == null) {
            throw new IllegalArgumentException("Account cannot be null");
        }
        if (user.getPassword() == null) {
            throw new IllegalArgumentException("Password cannot be null");
        }
        if (user.getState() == null) {
            throw new IllegalArgumentException("State cannot be null");
        }
        //设置更新时间为当前时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        if (user.getSalt() == null) {
            throw new IllegalArgumentException("Salt cannot be null");
        }
        return userMapper.insertSelective(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteByIds(List<Integer> ids) {
        return userMapper.deleteByIds(ids);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public int batchInsert(List<User> userList) {
        return userMapper.batchInsert(userList);
    }

    @Override
    public boolean isAccountExist(String account) {
        return userMapper.selectCountByAccount(account) != 0;
    }

    @Override
    public Integer getUserIdByAccount(String account) {
        return userMapper.selectUserIdByAccount(account);
    }

    @Override
    public int update(User user) {
        if (user == null) {
            throw new IllegalArgumentException("User cannot be null");
        }
        if (user.getId() == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User getByAccount(String account) {
        return userMapper.selectByAccount(account);
    }
}
